import logging
import time
import colorlog
from fastapi import Request


def setup_logging():
    """ 统一日志配置（终端输出） """

    # 创建彩色格式化器
    colored_formatter = colorlog.ColoredFormatter(
        "%(log_color)s%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        datefmt=None,
        reset=True,
        log_colors={
            'DEBUG': 'cyan',
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'red,bg_white',
        },
        secondary_log_colors={},
        style='%'
    )
    
    # 定义日志处理器
    handler = colorlog.StreamHandler()
    handler.setFormatter(colored_formatter)

    # 基础配置（输出到终端）
    logging.basicConfig(
        level=logging.INFO,
        handlers=[handler]  # 仅输出到终端
    )
    return logging.getLogger("fastapi")


# 请求日志中间件方法
async def log_requests(request: Request, call_next):
    """ 记录请求方法、路径、状态码和耗时 """
    logger = setup_logging()
    start_time = time.time()
    response = await call_next(request)
    process_time = (time.time() - start_time) * 1000

    logger.info(
        f"{request.method} {request.url.path} -> "
        f"Status: {response.status_code} | "
        f"Time: {process_time:.2f}ms"
    )
    return response